<script setup lang="ts">
import type { FormInstance } from 'ant-design-vue'
import { Modal, message } from 'ant-design-vue'
import { computed, h, onMounted, reactive, ref } from 'vue'
import type { Dayjs } from 'dayjs'
import dayjs from 'dayjs'

import { CheckCircleOutlined, CloseCircleOutlined, CopyOutlined, InfoCircleOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons-vue'
import axios from 'axios'
import { getRegistrationDetailApi, updateRegistrationApi } from '~/api/common/login'

defineOptions({
  name: 'Inovice',
})
const router = useRouter()
const route = useRoute()

const formRef = ref<FormInstance>()

// 表单状态
const formState = reactive<Record<string, any>>({
  username: JSON.parse(localStorage.getItem('userInfo') || '{}').userName,
  family_name: 'ZENG',
  given_name: 'Wei Jia',
  birth_date: '',
  title_en: 'Mr.',
  gender_en: 'male',
  gender: 1,
  examinee_number: '',
  phone: JSON.parse(localStorage.getItem('userInfo') || '{}').userPhone,
  landline: '',
  email: '19290112870@163.om',
  province: '河北省',
  city: '秦皇岛市',
  county: '北戴河区',
  address: '河北省 秦皇岛市 北戴河区',
  address_en: 'No.100 Jianguo Road, Chaoyang, Beijing',
  country_en: 'CHINA',
  subject_code: '1',
  exam_fee: 2000,
  registration_status: 1,
  makeup_unit: '',
  pre_exam_training: 1,
  company_name: JSON.parse(localStorage.getItem('userInfo') || '{}').userCompany,
  company_name_en: 'Bank of China',
  invoice_type: '',
  invoice_title: '',
  invoice_content: 'CDCS考试费',
  taxpayer_id: '',
  payment_proof: '',
  payment_time: null as Dayjs | null,
  invoice_issue_time: null as number | null,
})

// 报名详情数据
const registrationData = ref<any>(null)

// 发票相关字段已移除，以下函数保留以备将来需要
// 发票类型校验状态（已废弃）
// const invoiceTypeValidateStatus = ref('')
// const invoiceTypeHelpText = ref('')
// const invoiceTypeHasFeedback = ref(false)

// 发票抬头校验（已废弃）
// const invoiceTitleValidateStatus = ref('')
// const invoiceTitleHelpText = ref('')
// const invoiceTitleHasFeedback = ref(false)

// 纳税人识别号校验（已废弃）
// const taxpayerIdValidateStatus = ref('')
// const taxpayerIdHelpText = ref('')
// const taxpayerIdHasFeedback = ref(false)

// 发票开具时间校验（已废弃）
// const invoiceIssueTimeValidateStatus = ref('')
// const invoiceIssueTimeHelpText = ref('')
// const invoiceIssueTimeHasFeedback = ref(false)

// 缴费凭证校验（至少上传1个文件）
const voucherValidateStatus = ref('')
const voucherHelpText = ref('')
const voucherHasFeedback = ref(false)
const voucherFileList = ref<any[]>([])
// 跟踪正在上传的文件数量，用于控制提示框只显示一次
const uploadingFileCount = ref(0)

// 文件上传前验证
function beforeUpload(file: File) {
  // 验证文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件！')
    return false
  }

  // 验证文件大小（5MB）
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    message.error('图片大小不能超过 5MB！')
    return false
  }

  return true
}

function ensureFilePreviewUrl(file: any) {
  let finalUrl = file.url || file.thumbUrl || file.response?.url

  if (!finalUrl && file.originFileObj instanceof File) {
    if (!file.preview) {
      file.preview = URL.createObjectURL(file.originFileObj)
    }
    finalUrl = file.preview
  }

  if (finalUrl) {
    file.url = finalUrl
    file.thumbUrl = finalUrl
  }

  return finalUrl
}

function handleVoucherChange({ fileList }: any) {
  voucherFileList.value = (fileList || []).map((file: any) => {
    const finalUrl = ensureFilePreviewUrl(file)

    if (file.preview && finalUrl && finalUrl !== file.preview) {
      URL.revokeObjectURL(file.preview)
      file.preview = null
    }

    return file
  })
  // 更新表单中的 payment_proof，将多个URL用逗号分隔
  const urls = voucherFileList.value
    .filter((file: any) => {
      // 检查多种可能的URL来源
      const url = file.url || file.thumbUrl || file.response?.url
      return file.status === 'done' && url
    })
    .map((file: any) => file.url || file.thumbUrl || file.response?.url)
  formState.payment_proof = urls.join(',')
  validateVoucher(true)
}

// 预览图片相关
const previewVisible = ref(false)
const previewImageUrl = ref('')
function handlePreviewImage(file: any) {
  const imageUrl = file.url || file.thumbUrl || file.response?.url
  if (imageUrl) {
    previewImageUrl.value = imageUrl
    previewVisible.value = true
  }
  else {
    message.warning('图片加载失败，请重新上传')
  }
}

// 图片加载错误处理
function handleImageError(event: any, file: any) {
  console.error('图片加载失败:', file)
  // 可以设置一个默认的占位图
  const placeholder = ''
  if (event.target.src !== placeholder) {
    event.target.src = placeholder
  }
}
function handlePreviewCancel() {
  previewVisible.value = false
  previewImageUrl.value = ''
}

// 删除文件
function handleRemoveFile(index: number) {
  // 确认删除
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这张缴费凭证吗？',
    okText: '确定',
    icon: h(InfoCircleOutlined, { style: 'color:#376d9b;' }),
    cancelText: '取消',
    onOk: async () => {
      const removedFile = voucherFileList.value[index]
      if (removedFile?.preview) {
        URL.revokeObjectURL(removedFile.preview)
      }
      voucherFileList.value.splice(index, 1)
      // 更新表单中的 payment_proof
      const urls = voucherFileList.value
        .filter((file: any) => {
          const url = file.url || file.thumbUrl || file.response?.url
          return file.status === 'done' && url
        })
        .map((file: any) => file.url || file.thumbUrl || file.response?.url)
      formState.payment_proof = urls.length > 0 ? urls.join(',') : ''

      // 如果已经有订单ID，立即保存到后端
      const registration_id = route.query.orderId as string
      if (registration_id) {
        try {
          // 同步保存，确保删除操作立即生效
          await savePaymentProofToServer(registration_id, formState.payment_proof)
          Modal.info({
            title: '提示',
            content: h('div', { style: 'font-size:16px; line-height:24px; color:#333;' }, '删除成功'),
            icon: h(CheckCircleOutlined, { style: 'color:#376d9b;' }),
            okText: '确定',
            okButtonProps: { style: { backgroundColor: '#376d9b', border: 'none', borderRadius: '0' } } as any,
            centered: true,
          })
        }
        catch (err) {
          console.error('保存缴费凭证失败:', err)
          message.warning('删除成功，但保存到服务器失败，请刷新页面后重试')
        }
      }
      else {
        Modal.info({
          title: '提示',
          content: h('div', { style: 'font-size:16px; line-height:24px; color:#333;' }, '删除成功'),
          icon: h(CheckCircleOutlined, { style: 'color:#376d9b;' }),
          okText: '确定',
          okButtonProps: { style: { backgroundColor: '#376d9b', border: 'none', borderRadius: '0' } } as any,
          centered: true,
        })
      }

      if (voucherFileList.value.length === 0) {
        voucherValidateStatus.value = ''
        voucherHelpText.value = ''
        voucherHasFeedback.value = false
      }
      else {
        validateVoucher(true)
      }
    },
  })
}

// 保存缴费凭证到服务器
async function savePaymentProofToServer(registrationId: string, paymentProof: string) {
  try {
    console.log(registrationId, 'formState')
    const submitData = {
      ...formState,
      payment_proof: paymentProof,
      birth_date: formatDate(formState.birth_date),
      invoice_issue_time: formState.invoice_issue_time,
    }
    await updateRegistrationApi(submitData)
  }
  catch (error) {
    console.error('保存缴费凭证错误:', error)
    throw error
  }
}

// 格式化文件大小
function validateVoucher(_isBlur: boolean) {
  const fileCount = voucherFileList.value.filter((f: any) => {
    const url = f.url || f.thumbUrl || f.response?.url
    return f.status === 'done' && url
  }).length
  const value = formState.payment_proof

  // 缴费凭证改为非必填，所以只要有值就验证通过，没有值也不报错
  if (fileCount > 0 || value) {
    voucherValidateStatus.value = 'success'
    voucherHelpText.value = ''
    voucherHasFeedback.value = true
  }
  else {
    // 非必填，没有值也不显示错误
    voucherValidateStatus.value = ''
    voucherHelpText.value = ''
    voucherHasFeedback.value = false
  }
}

// 文件上传到云端
async function uploadFileToCloud(file: File): Promise<string | null> {
  try {
    const formData = new FormData()
    formData.append('subsystem_code', 'electricity-service')
    formData.append('subsystem_api', 'clue-macro-trace')
    formData.append('files', file)

    const response = await axios.post(
      'https://api-file-manage.airqualitychina.cn:9998/api/hold-filename-upload',
      formData,
      {
        timeout: 30000,
      },
    )

    const responseData = response.data

    // 检查上传是否成功
    if (responseData && responseData.code === 2000) {
      const resultData = responseData.result
      if (Array.isArray(resultData) && resultData.length > 0) {
        const filePath = resultData[0].url
        if (filePath) {
          // 构建完整URL
          const fullUrl = `https://f.hotgrid.cn/${filePath}`
          return fullUrl
        }
      }
    }

    message.error(responseData?.message || '上传失败，请重试')
    return null
  }
  catch (error: any) {
    console.error('文件上传错误:', error)
    message.error(error?.response?.data?.message || '上传失败，请重试')
    return null
  }
}

// 自定义上传处理函数
async function handleCustomRequest(options: any) {
  const { file, onSuccess, onError } = options

  // 增加正在上传的文件计数
  uploadingFileCount.value++

  try {
    const publicUrl = await uploadFileToCloud(file as File)

    if (publicUrl) {
      // 更新上传组件内部的文件对象，确保预览正常显示
      file.status = 'done'
      file.url = publicUrl
      file.thumbUrl = publicUrl
      file.response = { url: publicUrl }
      onSuccess({ url: publicUrl }, file)

      // 更新表单中的 payment_proof，将多个URL用逗号分隔
      const urls = voucherFileList.value
        .filter((f: any) => {
          const url = f.url || f.thumbUrl || f.response?.url
          return f.status === 'done' && url
        })
        .map((f: any) => f.url || f.thumbUrl || f.response?.url)
      formState.payment_proof = urls.join(',')

      // 把状态修改为OK
      voucherValidateStatus.value = 'success'
      voucherHelpText.value = ''
      voucherHasFeedback.value = true

      // 减少正在上传的文件计数
      uploadingFileCount.value--

      // 只有当所有文件都上传完成时才显示提示
      if (uploadingFileCount.value === 0) {
        Modal.info({
          title: '提示',
          content: h('div', { style: 'font-size:16px; line-height:24px; color:#333;' }, '凭证上传成功'),
          icon: h(CheckCircleOutlined, { style: 'color:#376d9b;' }),
          okText: '确定',
          okButtonProps: { style: { backgroundColor: '#376d9b', border: 'none', borderRadius: '0' } } as any,
          centered: true,
        })
      }
    }
    else {
      uploadingFileCount.value--
      onError(new Error('上传失败'))
    }
  }
  catch (error) {
    uploadingFileCount.value--
    onError(error)
  }
}

// 废弃的 company_name_en 英文公司名校验逻辑已移除，改用纳税人识别号 taxpayer_id 校验

// 配色主题（支付页）
const paymentTheme = ref<'theme-blue' | 'theme-emerald' | 'theme-orange' | 'theme-slate'>('theme-blue')
// 布局密度（支付页）
const paymentLayout = ref<'layout-compact' | 'layout-comfort' | 'layout-spacious'>('layout-comfort')

// 监听 invoice_type 变化（触发一次校验）

// 计算报名类型和费用信息
const paymentInfo = computed(() => {
  if (!registrationData.value) {
    return {
      subjectName: '',
      fee: 0,
      isMakeup: false,
    }
  }

  const makeupUnit = registrationData.value.makeup_unit
  let subjectName = registrationData.value.exam_subject?.description || ''
  let fee = registrationData.value.exam_subject?.exam_fee || registrationData.value.exam_fee || 0
  let isMakeup = false

  if (makeupUnit) {
    // 解析 makeup_unit，可能是字符串 "[1]" 或 "[1,2]" 或数组
    let makeupUnits: number[] = []
    try {
      if (typeof makeupUnit === 'string') {
        makeupUnits = JSON.parse(makeupUnit)
      } else if (Array.isArray(makeupUnit)) {
        makeupUnits = makeupUnit
      }
    } catch {
      // 如果解析失败，尝试直接使用
      makeupUnits = Array.isArray(makeupUnit) ? makeupUnit : []
    }

    // 如果 makeup_unit 存在且有效，处理补考逻辑
    if (makeupUnits.length > 0) {
      isMakeup = true
      // 移除科目名称最后4个字符，然后加上"补考报名"
      if (subjectName && subjectName.length >= 4) {
        subjectName = subjectName.slice(0, -4) + '补考报名'
      } else {
        subjectName = subjectName + '补考报名'
      }

      // 根据选择的单元数量确定费用
      const examSubject = registrationData.value.exam_subject as any
      if (makeupUnits.length === 2) {
        // 选择了两个单元 [1,2]
        fee = examSubject?.two_unit_fee || fee
      } else {
        // 只选择了一个单元 [1] 或 [2]
        fee = examSubject?.single_unit_fee || fee
      }
    }
  }

  return {
    subjectName,
    fee,
    isMakeup,
  }
})

// 页面加载时恢复暂存数据
onMounted(async () => {
  // 初次进入页面，清空缴费凭证相关状态
  voucherFileList.value = []
  formState.payment_proof = ''

  // 加载该考试报名的用户表单信息
  const registration_id = route.query.orderId as string
  if (registration_id) {
    try {
      const resp = await getRegistrationDetailApi(registration_id) as any
      if (resp.code === 0 && resp.data) {
        registrationData.value = resp.data
        console.log(registrationData.value.exam_subject.description, 'registrationData.value')
        // 同时更新 formState 以便表单使用
        Object.assign(formState, resp.data)
        formState.payment_proof = resp.data.payment_proof || ''

        // 如果有已保存的缴费凭证，加载到文件列表
        if (formState.payment_proof) {
          const urls = formState.payment_proof.split(',').filter((url: string) => url.trim())
          voucherFileList.value = urls.map((url: string, index: number) => ({
            uid: `existing-${index}-${Date.now()}`,
            name: `缴费凭证${index + 1}.jpg`,
            status: 'done',
            url: url.trim(),
            thumbUrl: url.trim(),
          }))
        }

        // 发票相关字段已移除，不再处理
        // if (resp.data.invoice_issue_time) {
        //   formState.invoice_issue_time = resp.data.invoice_issue_time
        // }
      }
    }
    catch (error) {
      console.error('加载报名详情失败:', error)
    }
  }
  else {
    console.log('无法获取到对应的id')
  }
})

function validateAllPersonalInfo() {
  // 缴费凭证改为非必填，只需要验证缴费凭证（如果有值的话）
  validateVoucher(true)

  // 缴费凭证非必填，所以只要有值就验证通过，没有值也不报错
  const ok = voucherValidateStatus.value !== 'error'
  return ok
}

// 提交用日期格式化（YYYY-MM-DD）
function formatDate(date: any): string | null {
  if (!date)
    return null
  if (typeof date === 'string')
    return date
  try {
    const dateObj = dayjs.isDayjs(date) ? date : dayjs(date)
    if (dateObj.isValid()) {
      return dateObj.format('YYYY-MM-DD')
    }
  }
  catch (e) {
    console.error('日期格式化错误:', e)
  }
  return null
}

// 提交功能（已废弃，改用handlePaymentSubmit）
// 保留此函数以防其他地方调用，但实际已不再使用
// @ts-expect-error
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async function handleSubmit() {
  // 此函数已废弃，保留以防其他地方调用
}

// 复制账户信息
function copyAccountInfo() {
  const accountInfo = `收款人：中国国际贸易促进委员会（中国国际商会）培训中心
开户行：中国光大银行学院路支行
账号：7505 0188 0001 41075`

  // 使用 Clipboard API
  if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard.writeText(accountInfo).then(() => {
      message.success('账户信息已复制到剪贴板')
    }).catch(() => {
      // 降级方案
      fallbackCopyText(accountInfo)
    })
  }
  else {
    // 降级方案
    fallbackCopyText(accountInfo)
  }
}

// 降级复制方案
function fallbackCopyText(text: string) {
  const textArea = document.createElement('textarea')
  textArea.value = text
  textArea.style.position = 'fixed'
  textArea.style.left = '-999999px'
  document.body.appendChild(textArea)
  textArea.focus()
  textArea.select()
  try {
    document.execCommand('copy')
    message.success('账户信息已复制到剪贴板')
  }
  catch (err) {
    message.error('复制失败，请手动复制')
  }
  document.body.removeChild(textArea)
}

// 我已缴费按钮处理
async function handlePaymentSubmit() {
  // 先进行表单验证
  const allOk = validateAllPersonalInfo()
  if (!allOk) {
    // validation failed
    return
  }

  // 显示确认对话框，防止误操作
  Modal.confirm({
    title: '确认缴费',
    content: h('div', { style: 'font-size:16px; line-height:24px; color:#333;' }, [
      h('p', { style: 'margin-bottom: 8px;' }, ''),
      h('p', { style: 'margin: 0; color: #666;' }, '确认我已完成缴费，是否提交？'),
    ]),
    icon: h(InfoCircleOutlined, { style: 'color:#376d9b;' }),
    okText: '是',
    cancelText: '否',
    okButtonProps: { style: { backgroundColor: '#376d9b', border: 'none', borderRadius: '0' } } as any,
    cancelButtonProps: { style: { borderRadius: '0' } } as any,
    centered: true,
    onOk: async () => {
      try {
        // 提交成功把这个状态改为2（已缴费待审核）
        formState.registration_status = 2
        // 支付时间为当前创建成功时间
        formState.payment_time = dayjs().format('YYYY-MM-DD HH:mm:ss')
        const submitData = {
          ...formState,
          birth_date: formatDate(formState.birth_date),
          invoice_issue_time: formState.invoice_issue_time,
        }
        const response = await updateRegistrationApi(submitData) as any
        console.log(response.code, response.code, submitData)

        // 判断提交是否成功
        if (response && (response.code === 0 || response.code === '200' || response.success)) {
          // 提交成功后清除暂存数据
          localStorage.removeItem('registrationDraft')

          Modal.info({
            title: '提示',
            content: h('div', { style: 'font-size:16px; line-height:24px; color:#333;' }, '已提交，等待审核'),
            icon: h(CheckCircleOutlined, { style: 'color:#376d9b;' }),
            okText: '确定',
            okButtonProps: { style: { backgroundColor: '#376d9b', border: 'none', borderRadius: '0' } } as any,
            centered: true,
            onOk: () => {
              router.push('/myexamlist/myExam')
            },
          })
        }
        else {
          // 提交失败，显示错误信息
          const errorMsg = response?.message || '提交失败，请重试'
          message.error(errorMsg)
        }
      }
      catch (errorInfo: any) {
        console.log('Failed:', errorInfo)
        const errorMsg = errorInfo?.response?.data?.message || errorInfo?.message || '提交失败，请重试'
        message.error(errorMsg)
      }
    },
  })
}
</script>

<template>
  <page-container>
    <div
      style="
            position:relative;
            top:-21px;
            "
      class="payment-page" :class="[paymentTheme, paymentLayout]"
    >
      <!-- 主题与布局切换（默认隐藏，需要时可将 display 改为 block） -->
      <div style="display:none; text-align:right; padding: 8px 0 0 0;">
        <a-space>
          <a-radio-group v-model:value="paymentTheme" button-style="solid" size="small">
            <a-radio-button value="theme-blue">
              蓝色
            </a-radio-button>
            <a-radio-button value="theme-emerald">
              蓝绿
            </a-radio-button>
            <a-radio-button value="theme-orange">
              橙色
            </a-radio-button>
            <a-radio-button value="theme-slate">
              石板灰
            </a-radio-button>
          </a-radio-group>
          <a-radio-group v-model:value="paymentLayout" button-style="solid" size="small">
            <a-radio-button value="layout-compact">
              紧凑
            </a-radio-button>
            <a-radio-button value="layout-comfort">
              舒适
            </a-radio-button>
            <a-radio-button value="layout-spacious">
              宽松
            </a-radio-button>
          </a-radio-group>
        </a-space>
      </div>

      <!-- 开票与凭证 55 109 155 -->
      <div class="section-body">
        <div class="payment-guide-wrapper">
          <div class="payment-guide-title">
            缴费指南
          </div>
          <div class="payment-guide-note">
            <InfoCircleOutlined />
            <span>请在报名提交后及时缴费，以免影响考试资格。</span>
          </div>
          <div
            v-if="registrationData && paymentInfo.subjectName"
            style="
            font-size: 16px;
            "
          >
            <span>{{ paymentInfo.subjectName }}报名费</span>
            <span><strong>{{ paymentInfo.fee }}</strong> 元（含电子教材/证书等）</span>
          </div>
          <div class="payment-guide-grid">
            <div class="" style="position: relative;">
              <div class="guide-card-title">
                方式一 · 转账汇款
              </div>
              <p class="guide-card-desc">
                通过银行转账支付，请确保填写完整的账户信息。
              </p>
              <div class="account-info">
                <a-button
                  type="text"
                  size="small"
                  class="copy-account-btn"
                  @click="copyAccountInfo"
                >
                  <CopyOutlined />
                  一键复制
                </a-button>
                <div class="info-row">
                  <span class="info-label">收款人</span>
                  <span class="info-value">中国国际贸易促进委员会（中国国际商会）培训中心</span>
                </div>
                <div class="info-row">
                  <span class="info-label">开户行</span>
                  <span class="info-value">中国光大银行学院路支行</span>
                </div>
                <div class="info-row">
                  <span class="info-label">账&nbsp;&nbsp;号</span>
                  <span class="info-value">7505 0188 0001 41075</span>
                </div>
              </div>
              <span
                style="
                color:red;
                font-size:16px;
                "
              >
                **温馨提示：
                汇款时，考生或代付款人请在附言中注明考生姓名及考试名称，如“姓名 CDCS”。汇款完成后请注意保留汇款凭证截图。
              </span>
            </div>
            <div class="">
              <div class="guide-card-title">
                方式二 · 支付宝二维码
              </div>
              <p
                style="
                font-size: 16px;
                "
                class="guide-card-desc"
              >
                扫描中国贸促会培训中心官方支付宝二维码完成缴费。
              </p>
              <div 
              style="
              text-align: center;
              "
              >
                <img
                  src="/pay_aliyun.jpg"
                  alt="支付宝支付二维码"
                  class="qr-image"
                />
              </div>
            </div>
          </div>
        </div>
        <a-form
          ref="formRef"
          style="
              position: relative;
              box-shadow: none;
              border:none;
              background-color: #ffffff;
              padding:20px
              "
          :model="formState"
        >
          <br>
          <a-form-item
            class=""
            name="payment_voucher"
            :required="false"
            :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
            :wrapper-col="{ lg: { span: 10 }, sm: { span: 17 } }"
            :validate-status="voucherValidateStatus"
            :help="voucherHelpText"
            :has-feedback="voucherHasFeedback"
          >
            <template #label>
              <span style="font-size: 16px; color:#333; font-weight: 600;">缴费凭证</span>
            </template>
            <div
              style="display: flex; flex-direction: column; align-items: flex-start; gap: 16px; width: 100%;"
            >
              <!-- 上传组件 - 首次上传按钮（仅在未上传时显示） -->
              <a-upload
                v-show="voucherFileList.length === 0"
                v-model:file-list="voucherFileList"
                :custom-request="handleCustomRequest"
                :show-upload-list="false"
                :max-count="10"
                accept="image/jpeg,image/jpg,image/png,image/gif,image/webp"
                :before-upload="beforeUpload"
                class="voucher-upload-wrapper"
                multiple
                @change="handleVoucherChange"
              >
                <a-button type="primary" size="large" class="custom-upload-btn">
                  <UploadOutlined />
                  <span style="margin-left: 8px;">点击上传</span>
                </a-button>
              </a-upload>

              <!-- 已上传文件展示区 -->
              <div v-if="voucherFileList.length > 0" class="uploaded-files">
                <!-- <p class="file-count">已上传 {{ voucherFileList.length }} 张，最多10张</p> -->
                <div class="file-thumbnails">
                  <!-- 显示已上传图片缩略图 -->
                  <div
                    v-for="(file, index) in voucherFileList"
                    :key="file.uid || index"
                    class="file-thumbnail"
                  >
                    <img
                      :src="file.url || file.thumbUrl || file.response?.url"
                      alt="上传预览"
                      class="thumbnail-img"
                      @error="handleImageError($event, file)"
                      @click="handlePreviewImage(file)"
                    >
                    <CloseCircleOutlined
                      class="delete-icon"
                      @click.stop="handleRemoveFile(index)"
                    />
                  </div>
                  <!-- 追加“继续上传”虚线加号卡片 -->
                  <a-upload
                    v-if="voucherFileList.length < 10"
                    v-model:file-list="voucherFileList"
                    :custom-request="handleCustomRequest"
                    :show-upload-list="false"
                    :max-count="10"
                    accept="image/jpeg,image/jpg,image/png,image/gif,image/webp"
                    :before-upload="beforeUpload"
                    class="voucher-upload-wrapper"
                    multiple
                    @change="handleVoucherChange"
                  >
                    <div class="file-thumbnail add-tile">
                      <PlusOutlined class="add-icon" />
                    </div>
                  </a-upload>
                </div>
              </div>

              <!-- 备注：继续上传已集成于加号卡片 -->

              <!-- 提示文字 -->
            </div>
            <span
              style="display:block; margin-top:8px; color:gray; opacity:0.9; font-size:16px; white-space:normal; line-height: 20px;"
            >
              支持 JPG、PNG 格式，每张图片不超过 5MB。（非必传项）
            </span>
          </a-form-item>

          <input v-model="formState.title_en" type="hidden">
          <input v-model="formState.gender_en" type="hidden">
        </a-form>

        <!-- 固定底部按钮 -->
        <div
          style="
    padding-top:33px;
    "
        >
          <center>
            <a-button
              type="primary"
              class="btn-ccpit btn-ccpit-primary "
              @click="handlePaymentSubmit"
            >
              我已缴费
            </a-button>
          </center>
        </div>
      </div>
    </div>

    <Modal
      v-model:open="previewVisible"
      :footer="null"
      :width="800"
      centered
      class="image-preview-modal"
      @cancel="handlePreviewCancel"
    >
      <img
        :src="previewImageUrl"
        alt="缴费凭证预览"
        style="width: 100%; max-height: 70vh; object-fit: contain;"
      >
    </Modal>
  </page-container>
</template>

<style scoped>
@import './index.css';
/* ===== 布局密度（不改动业务结构，仅调整留白/圆角/阴影） ===== */
.hero-card {
  margin: 8px 0 16px 0;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 14px 32px -18px rgba(42, 84, 156, 0.28);
}
.hero-card :deep(.ant-card-body) {
  padding: 18px 20px;
}
.hero-head {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  gap: 12px;
}
.hero-title {
  font-size: 20px;
  font-weight: 700;
  color: #1f2937;
}
.hero-meta {
  display: flex;
  align-items: baseline;
  gap: 8px;
}
.hero-price-label {
  color: #64748b;
  font-size: 14px;
}
.hero-price {
  font-size: 20px;
  font-weight: 700;
  color: #0f172a;
}
.hero-sub {
  margin-top: 6px;
  color: #4b5563;
}
.hero-badge {
  color: #64748b;
  margin-right: 6px;
}
.hero-desc {
  margin-top: 8px;
  color: #6b7280;
  font-size: 14px;
}

.section-card {
  margin: 14px 0;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 10px 26px -18px rgba(31, 41, 55, 0.22);
}
.section-card :deep(.ant-card-head) {
  border-bottom: 1px solid #f0f2f5;
}
.section-card :deep(.ant-card-body) {
  padding: 16px 18px;
}
.section-title {
  font-size: 16px;
  font-weight: 700;
  color: #1f2937;
}
.section-body {
  height:87vh;
  overflow-y: scroll;
  margin-top: 1px;
  padding-bottom: 80px;
  margin-bottom: 40px;
}

@media (max-height: 800px) {
  .section-body {
    height: calc(100vh - 100px);
    padding-bottom: 60px;
    margin-bottom: 30px;
  }
}

.payment-guide-wrapper {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 24px;
  border: 1px solid #e2e8f0;
  border-radius: 16px;
  background: linear-gradient(135deg, #f7fbff 0%, #ffffff 100%);
  margin-bottom: 16px;
}

.payment-guide-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.payment-guide-icon {
  font-size: 28px;
  color: #376d9b;
}

.payment-guide-title {
  font-size: 20px;
  font-weight: 700;
  color: #1f2937;
}

.payment-guide-desc {
  margin: 4px 0 0 0;
  color: #4b5563;
  font-size: 14px;
}

.payment-fee-brief {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  font-size: 15px;
  color: #1f2937;
  background: #f1f5f9;
  border: 1px solid #d8e3f0;
  border-radius: 10px;
  padding: 12px 16px;
}

.payment-guide-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
  gap: 16px;
}

.guide-card {
  border: 1px solid #dde7f4;
  border-radius: 14px;
  padding: 20px;
  background: #fff;
  box-shadow: 0 12px 30px -22px rgba(55, 109, 155, 0.6);
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.guide-card-title {
  font-size: 16px;
  font-weight: 600;
  color: #123457;
}

.guide-card-desc,
.qr-tip {
  margin: 0;
  color: #516074;
  font-size: 16px;
  line-height: 1.6;
}

.account-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 12px;
  background: #f8fbff;
  border: 1px dashed #bed5f3;
  border-radius: 10px;
  position: relative;
}

.copy-account-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 10;
  color: #376d9b;
  font-size: 12px;
  padding: 2px 8px;
  height: auto;
  display: flex;
  align-items: center;
  gap: 4px;
}

.copy-account-btn:hover {
  color: #1890ff;
  background: rgba(24, 144, 255, 0.1);
}

.info-row {
  display: flex;
  gap: 12px;
  font-size: 14px;
  color: #1f2937;
}

.info-label {
  min-width: 52px;
  color: #6b7280;
}

.info-value {
  flex: 1;
  font-weight: 600;
  color: #0f172a;
}

.qr-card {
  position: relative;
}

.qr-placeholder {
  height: 200px;
  border: 2px dashed #d1d9e8;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 6px;
  color: #64748b;
  background: #fdfefe;
  font-weight: 600;
}

.qr-placeholder small {
  font-size: 12px;
  color: #9aa5b5;
  font-weight: normal;
}

.qr-image-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px;
  background: #fff;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.qr-image {
  max-width: 100%;
  max-height: 300px;
  width: auto;
  height: auto;
  border-radius: 8px;
  object-fit: contain;
}

.payment-guide-note {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  padding: 12px 16px;
  border-radius: 10px;
  background: #fef6e4;
  border: 1px solid #f8e7c5;
  color: #7a4b00;
  font-size: 14px;
  line-height: 1.6;
}

.payment-guide-note .anticon {
  font-size: 18px;
  color: #d97706;
  margin-top: 2px;
}

@media (max-width: 768px) {
  .payment-guide-wrapper {
    padding: 16px;
  }
}

.payment-page.layout-compact .subject-header {
  margin-bottom: 8px;
}
.payment-page.layout-compact .transfer-info-item {
  margin-top: 8px;
}
.payment-page.layout-compact :deep(.ant-form) {
  padding: 12px !important;
}
.payment-page.layout-compact :deep(.ant-form-item) {
  margin-bottom: 12px;
}
.payment-page.layout-compact :deep(.ant-input) {
  height: 30px;
}
.payment-page.layout-compact :deep(.ant-btn) {
  height: 34px;
}

.payment-page.layout-comfort .subject-header {
  margin-bottom: 12px;
}
.payment-page.layout-comfort .transfer-info-item {
  margin-top: 12px;
}
.payment-page.layout-comfort :deep(.ant-form) {
  padding: 20px !important;
}
.payment-page.layout-comfort :deep(.ant-form-item) {
  margin-bottom: 16px;
}
.payment-page.layout-comfort :deep(.ant-input) {
  height: 34px;
}
.payment-page.layout-comfort :deep(.ant-btn) {
  height: 36px;
}

.payment-page.layout-spacious .subject-header {
  margin-bottom: 16px;
}
.payment-page.layout-spacious .transfer-info-item {
  margin-top: 16px;
}
.payment-page.layout-spacious :deep(.ant-form) {
  padding: 26px !important;
}
.payment-page.layout-spacious :deep(.ant-form-item) {
  margin-bottom: 20px;
}
.payment-page.layout-spacious :deep(.ant-input) {
  height: 38px;
}
.payment-page.layout-spacious :deep(.ant-btn) {
  height: 40px;
}

/* ===== 支付页主题（与列表/详情保持一致风格） ===== */
.theme-blue .back-button {
  color: #2a4e73;
}
.theme-blue .msg_title {
  color: #2a4e73;
  font-weight: 600;
}
.theme-blue .transfer-info-label {
  color: #335a82;
  font-weight: 600;
}
.theme-blue .descriptions-demo :deep(.ant-collapse>.ant-collapse-item>.ant-collapse-header) {
  color: #2a4e73;
}
.theme-blue .non-collapsible :deep(.ant-collapse-item) {
  box-shadow: 0 10px 30px -15px rgba(55, 109, 155, 0.18);
}

.theme-emerald .back-button {
  color: #0b5f56;
}
.theme-emerald .msg_title {
  color: #0b5f56;
  font-weight: 600;
}
.theme-emerald .transfer-info-label {
  color: #0f766e;
  font-weight: 600;
}
.theme-emerald .descriptions-demo :deep(.ant-collapse>.ant-collapse-item>.ant-collapse-header) {
  color: #0b5f56;
}
.theme-emerald .non-collapsible :deep(.ant-collapse-item) {
  box-shadow: 0 10px 30px -15px rgba(16, 185, 129, 0.18);
}

.theme-orange .back-button {
  color: #9a3412;
}
.theme-orange .msg_title {
  color: #9a3412;
  font-weight: 600;
}
.theme-orange .transfer-info-label {
  color: #a16207;
  font-weight: 600;
}
.theme-orange .descriptions-demo :deep(.ant-collapse>.ant-collapse-item>.ant-collapse-header) {
  color: #9a3412;
}
.theme-orange .non-collapsible :deep(.ant-collapse-item) {
  box-shadow: 0 10px 30px -15px rgba(245, 158, 11, 0.18);
}

.theme-slate .back-button {
  color: #374151;
}
.theme-slate .msg_title {
  color: #1f2937;
  font-weight: 600;
}
.theme-slate .transfer-info-label {
  color: #4b5563;
  font-weight: 600;
}
.theme-slate .descriptions-demo :deep(.ant-collapse>.ant-collapse-item>.ant-collapse-header) {
  color: #1f2937;
}
.theme-slate .non-collapsible :deep(.ant-collapse-item) {
  box-shadow: 0 10px 30px -15px rgba(55, 65, 81, 0.18);
}

/* 通用元素适配当前简化结构 */
.payment-page .subject-header .subject-divider {
  margin: 8px 0 0 0;
}
.payment-page .msg_title {
  font-weight: 600;
}
.payment-page .transfer-info-label {
  font-weight: 600;
}
.payment-page :deep(.ant-form) {
  background: #fff;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.08);
  border-radius: 6px;
}

/* 与报名表单保持一致的字体与控件风格 */
.payment-page :deep(.ant-form-item-label > label),
.payment-page :deep(.ant-input),
.payment-page :deep(.ant-input-number),
.payment-page :deep(.ant-select-selector),
.payment-page :deep(.ant-picker),
.payment-page :deep(textarea),
.payment-page :deep(input),
.payment-page :deep(button) {
  font: 16px / 1.5 "Helvetica Neue", Helvetica, "PingFang SC", "Microsoft YaHei", "Hiragino Sans GB", "WenQuanYi Micro Hei", Arial, "SimSun", "sans-serif";
}
.payment-page :deep(.ant-input),
.payment-page :deep(.ant-input-number),
.payment-page :deep(.ant-select-selector),
.payment-page :deep(.ant-picker) {
  border-radius: 0;
}
.payment-page :deep(.ant-btn) {
  border-radius: 0;
}
div::-webkit-scrollbar {
  width: 5px; /* 滚动条宽度 */
}
div::-webkit-scrollbar-thumb {
  background-color: rgba(87, 110, 129, 0.3); /* 半透明黑色，你可以根据需要调整透明度 */
  border-radius: 4px; /* 滑块圆角 */
}

/* ===== 上传缴费凭证样式 ===== */
.voucher-upload-wrapper :deep(.ant-upload-select) {
  width: auto;
  margin: 0;
  border: none;
  background: transparent;
}

.voucher-upload-wrapper :deep(.ant-upload-select-picture-card) {
  width: auto;
  height: auto;
  border: none;
  background: transparent;
}

.voucher-upload-wrapper :deep(.ant-upload-list) {
  display: none;
}

/* 上传按钮样式 */
.upload-primary-btn {
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
  transition: all 0.3s ease;
}

.upload-primary-btn:hover {
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
  transform: translateY(-1px);
}

/* 上传提示样式 */
.upload-tips {
  margin-top: 8px;
  padding: 12px 16px;
  background: #f6f8fa;
  border-radius: 6px;
}

.upload-tips-title {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.upload-tips-list {
  margin: 0;
  padding-left: 20px;
  list-style: none;
}

.upload-tips-list li {
  font-size: 15px;
  color: #666;
  line-height: 1.8;
  position: relative;
  padding-left: 12px;
}

.upload-tips-list li::before {
  content: '•';
  position: absolute;
  left: 0;
  color: #2177c7;
  font-weight: bold;
}

/* 方案2：卡片式风格 */
.upload-btn-style-2 {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
  padding: 40px 24px;
  border: 2px solid #e8e8e8;
  border-radius: 12px;
  background: #fff;
  cursor: pointer;
  transition: all 0.3s ease;
  width: 100%;
  box-sizing: border-box;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.upload-btn-style-2:hover {
  border-color: #1890ff;
  box-shadow: 0 4px 16px rgba(24, 144, 255, 0.15);
  transform: translateY(-2px);
}

.upload-icon-large {
  font-size: 48px;
  color: #1890ff;
}

.upload-text-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.upload-title-card {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.upload-hint-card {
  font-size: 14px;
  color: #8c8c8c;
}

/* 方案3：图标突出风格 */
.upload-btn-style-3 {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 32px 24px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background: #fff;
  cursor: pointer;
  transition: all 0.3s ease;
  width: 100%;
  box-sizing: border-box;
}

.upload-btn-style-3:hover {
  border-color: #1890ff;
  background: #f0f8ff;
}

.upload-icon-circle {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 64px;
  height: 64px;
  background: #1890ff;
  border-radius: 50%;
  color: #fff;
  font-size: 32px;
  transition: all 0.3s ease;
}

.upload-btn-style-3:hover .upload-icon-circle {
  background: #40a9ff;
  transform: scale(1.1);
}

.upload-text-simple {
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

/* 方案4：拖拽上传风格 */
.upload-btn-style-4 {
  width: 100%;
  box-sizing: border-box;
}

.upload-drag-area {
  padding: 60px 24px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background: #fafafa;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
}

.upload-drag-area:hover {
  border-color: #1890ff;
  background: #f0f8ff;
}

.upload-drag-icon {
  font-size: 56px;
  color: #1890ff;
  margin-bottom: 16px;
}

.upload-drag-text {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.upload-drag-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.upload-drag-hint {
  font-size: 14px;
  color: #8c8c8c;
  margin: 0;
}

/* 预览容器样式 */
.voucher-preview-container {
  width: 100%;
  margin-top: 8px;
}

.voucher-preview-title {
  display: flex;
  align-items: center;
  font-size: 14px;
  font-weight: 600;
  color: #52c41a;
  margin-bottom: 12px;
}

.voucher-preview-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  width: 100%;
}

@media (max-width: 768px) {
  .voucher-preview-item {
    max-width: 100%;
  }
}

.voucher-preview-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px;
  height: 120px;
  border: 1px solid #e8e8e8;
  border-radius: 1px;
  background: #fff;
  transition: all 0.3s ease;
  width: 100%;
  max-width: 200px;
}

.voucher-preview-item:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
}

.preview-image-wrapper {
  position: relative;
  width: 100%;
  height: 50px;
  border-radius: 2px;
  overflow: hidden;
  cursor: pointer;
  background: #ffffff;
  border: none;
}

.preview-image {
  border:none;
  width: 100%;
  height: 100%;
  object-fit: contain;
  transition: transform 0.3s ease;
}

.preview-image-wrapper:hover .preview-image {
  transform: scale(1.05);
}

.payment-voucher-item{
  float: left;
  width: 900px;
}

.preview-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.preview-image-wrapper:hover .preview-overlay {
  opacity: 1;
}

.preview-btn {
  color: #fff !important;
  border-color: rgba(255, 255, 255, 0.3) !important;
}

.preview-btn:hover {
  background: rgba(255, 255, 255, 0.2) !important;
  border-color: rgba(255, 255, 255, 0.5) !important;
}

.preview-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  width: 100%;
}

.preview-name {
  font-size: 14px;
  font-weight: 500;
  color: #6e6e6e;
  word-break: break-all;
}

.preview-size {
  font-size: 12px;
  color: #8c8c8c;
}

/* 预览模态框样式 */
.image-preview-modal :deep(.ant-modal-body) {
  padding: 24px;
  text-align: center;
}

.image-preview-modal :deep(.ant-modal-close) {
  color: #fff;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  width: 32px;
  height: 32px;
  top: 16px;
  right: 16px;
}

.image-preview-modal :deep(.ant-modal-close:hover) {
  background: rgba(0, 0, 0, 0.7);
}

/* 上传按钮样式 */
.custom-upload-btn {
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
  transition: all 0.3s ease;
}

.custom-upload-btn:hover {
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
  transform: translateY(-1px);
}

/* 已上传文件展示区 */
.uploaded-files {
  margin-top: 16px;
  width: 100%;
}

.file-count {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
  font-weight: 500;
}

.file-thumbnails {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  width: 100%;
}

.file-thumbnail {
  position: relative;
  width: 120px;
  height: 120px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  overflow: hidden;
  background: #f5f5f5;
  transition: all 0.3s ease;
}

.file-thumbnail:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
}

.thumbnail-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  cursor: pointer;
  transition: transform 0.3s ease;
  background: #f5f5f5;
}

.thumbnail-img:hover {
  transform: scale(1.05);
}

.delete-icon {
  position: absolute;
  bottom: 4px;
  right: 1px;
  top:1px;
  font-size: 22px;
  color: #ff4d4f;
  background: #fff;
  border-radius: 50%;
  cursor: pointer;
  z-index: 10;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  padding: 2px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-icon:hover {
  color: #ff7875;
  transform: scale(1.1);
  box-shadow: 0 4px 8px rgba(255, 77, 79, 0.3);
}

/* 固定底部按钮 */
.fixed-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #ffffff;
  border-top: 1px solid #e8e8e8;
  padding: 16px 24px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
  z-index: 100;
  display: flex;
  justify-content: center;
  align-items: center;
}

.payment-submit-btn {
  min-width: 200px;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
}

/* 为页面内容添加底部padding，避免被固定footer遮挡 */
.payment-page {
  padding-bottom: 100px;
}

/* 追加上传的"加号卡片"样式 */
.add-tile {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #d9d9d9;
  background: #fff;
  cursor: pointer;
}
.add-tile:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
}
.add-icon {
  font-size: 28px;
  color: #999;
}
</style>
